package com.gly091020.GLYCan.block.entity;

import com.gly091020.GLYCan.block.CanBlock;
import com.gly091020.GLYCan.util.CanContainer;
import com.gly091020.GLYCan.GLYCanMod;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.world.ContainerHelper;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.NotNull;

public class CanBlockEntity extends BlockEntity implements CanContainer {
    public NonNullList<ItemStack> stacks = NonNullList.withSize(
            10,
            ItemStack.EMPTY
    );
    public int color = CanBlock.NORMAL_COLOR;
    public CanBlockEntity(BlockPos pos, BlockState blockState) {
        super(GLYCanMod.CAN_BLOCK_ENTITY.get(), pos, blockState);
    }

    @Override
    protected void saveAdditional(CompoundTag tag, HolderLookup.Provider provider) {
        super.saveAdditional(tag, provider);
        ContainerHelper.saveAllItems(tag, stacks, provider);
        tag.putInt("color", color);
    }

    @Override
    protected void loadAdditional(CompoundTag tag, HolderLookup.Provider provider) {
        super.loadAdditional(tag, provider);
        ContainerHelper.loadAllItems(tag, stacks, provider);
        color = tag.getInt("color");
    }

    @Override
    public void handleUpdateTag(CompoundTag tag, HolderLookup.Provider lookupProvider) {
        super.handleUpdateTag(tag, lookupProvider);
        ContainerHelper.loadAllItems(tag, stacks, lookupProvider);
        color = tag.getInt("color");
    }

    @Override
    public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider lookupProvider) {
        super.onDataPacket(net, pkt, lookupProvider);
        var tag = pkt.getTag();
        ContainerHelper.loadAllItems(tag, stacks, lookupProvider);
        color = tag.getInt("color");
    }

    @Override
    public CompoundTag getUpdateTag(HolderLookup.Provider registries) {
        var t = super.getUpdateTag(registries);
        ContainerHelper.saveAllItems(t, stacks, registries);
        t.putInt("color", color);
        return t;
    }

    @Override
    public @NotNull NonNullList<ItemStack> getItems() {
        return stacks;
    }
}
